import { view } from 'cc';
import { UITransform } from 'cc';
import { director } from 'cc';
import { _decorator } from 'cc';
import BaseComp from '../../common/BaseComp';
import NDB from '../../common/NDBTS';
import { resourceManager } from '../../common/ResourceManager';
import { GameConfig } from '../../GameConfig';
import { eliminateGameManager } from './EliminateGameManager';
import { Sprite } from 'cc';
import { SpriteFrame } from 'cc';
import { RenderTexture } from 'cc';
import { Texture2D } from 'cc';
import { ImageAsset } from 'cc';
import { Vec3 } from 'cc';
import { Animation } from 'cc';
import { Scene } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EliminatePause')
export class EliminatePause extends BaseComp {

    private d3Blur: Sprite = null;
    private uiBlur: Sprite = null;

    private _renderTexture3D: RenderTexture = null;
    private _renderTextureUI: RenderTexture = null;

    private content: Animation = null;

    private capCanvas: HTMLCanvasElement = null;


    __preload(): void {
        this.openFilter = true;
        super.__preload();
    }

    protected onLoad(): void {

        const maskNode = this.node.getChildByName('mask');
        console.log("visible size is ", view.getVisibleSize());
        maskNode.getComponent(UITransform).width = view.getVisibleSize().width;
        maskNode.getComponent(UITransform).height = view.getVisibleSize().height;

        const d3BlurMat = this.d3Blur.customMaterial;
        const uiBlurMat = this.uiBlur.customMaterial;
        d3BlurMat && d3BlurMat.setProperty('resolutionX', view.getDesignResolutionSize().width);
        d3BlurMat && d3BlurMat.setProperty('resolutionY', view.getDesignResolutionSize().height);

        uiBlurMat && uiBlurMat.setProperty('resolutionX', view.getDesignResolutionSize().width);
        uiBlurMat && uiBlurMat.setProperty('resolutionY', view.getDesignResolutionSize().height);

    }

    onEnable(): void {
        // this.cap3DCameraAndUICamera();
    }

    /** 截取3d摄像机和UI摄像机的内容 */
    cap3DCameraAndUICamera() {
        let _renderTexture3D = new RenderTexture();
        let _renderTextureUI = new RenderTexture();

        const designSize = view.getDesignResolutionSize();
        console.log("design size is ", designSize);

        const w = Math.floor(designSize.width);
        const h = Math.floor(designSize.height);

        _renderTexture3D.reset({
            width: w,
            height: h
        });
        _renderTextureUI.reset({
            width: w,
            height: h
        });
        // eliminateGameManager.uiManager.UICamera.clearColor = math.color().fromHEX('#2E313A00');
        eliminateGameManager.uiManager.camera.targetTexture = _renderTexture3D;
        eliminateGameManager.uiManager.UICamera.targetTexture = _renderTextureUI;

        // 组合图像
        this.capCanvas = document.createElement('canvas');
        // @ts-ignore
        let ctx = this.capCanvas.getContext('2d');

        this.capCanvas.width = Math.floor(designSize.width);
        this.capCanvas.height = Math.floor(designSize.height);

        this.scheduleOnce(() => {
            console.log("读取相机渲染数据");

            const generateUI = () => {

                let pixelsUI = new Uint8Array(_renderTextureUI.width * _renderTextureUI.height * 4);
                _renderTextureUI.readPixels(0, 0, _renderTextureUI.width, _renderTextureUI.height, pixelsUI);


                let imageDataUI = ctx.createImageData(_renderTextureUI.width, _renderTextureUI.height);
                imageDataUI.data.set(pixelsUI);
                ctx.putImageData(imageDataUI, 0, 0);

                ctx.globalCompositeOperation = 'destination-over';
                ctx.fillStyle = '#2E313A01';  // 你想要的背景颜色
                ctx.fillRect(0, 0, this.capCanvas.width, this.capCanvas.height);
                let dataURL = this.capCanvas.toDataURL("image/png");

                let image = new Image(this.capCanvas.width, this.capCanvas.height);
                image.src = dataURL;

                image.onload = () => {
                    const imageAsset = new ImageAsset(image);
                    let texture = new Texture2D();
                    texture.image = imageAsset;

                    let frame = new SpriteFrame();
                    frame.texture = texture;
                    this.uiBlur.spriteFrame = frame;
                    this.uiBlur.node.scale = new Vec3(1, -1, 1);

                    _renderTextureUI.destroy() && (_renderTextureUI = null);
                }
            }

            const generate3D = () => {
                // 读取像素数据
                let pixels3D = new Uint8Array(_renderTexture3D.width * _renderTexture3D.height * 4);

                _renderTexture3D.readPixels(0, 0, _renderTexture3D.width, _renderTexture3D.height, pixels3D);

                // 组合图像
                // let canvas = document.createElement('canvas');
                // let ctx = canvas.getContext('2d');

                let imageData3D = ctx.createImageData(_renderTexture3D.width, _renderTexture3D.height);


                imageData3D.data.set(pixels3D);
                // 假设UI元素应该被渲染在3D内容之上
                ctx.putImageData(imageData3D, 0, 0);

                ctx.globalCompositeOperation = 'destination-over';
                ctx.fillStyle = "#2E313A";  // 你想要的背景颜色
                ctx.fillRect(0, 0, this.capCanvas.width, this.capCanvas.height);

                let dataURL = this.capCanvas.toDataURL("image/png");

                let image = new Image(this.capCanvas.width, this.capCanvas.height);
                image.src = dataURL;

                image.onload = () => {
                    const imageAsset = new ImageAsset(image);
                    let texture = new Texture2D();
                    texture.image = imageAsset;

                    let frame = new SpriteFrame();
                    frame.texture = texture;
                    this.d3Blur.spriteFrame = frame;
                    this.d3Blur.node.scale = new Vec3(1, -1, 1);

                    _renderTexture3D.destroy() && (_renderTexture3D = null);
                }
            }

            generateUI();
            generate3D();
            // eliminateGameManager.uiManager.UICamera.clearColor = math.color().fromHEX('#2E313A00');
        }, 0);
    }

    start() {
        this.content.play("toast");
        this.content.on(Animation.EventType.FINISHED, () => {
            console.log("播放完毕");
            director.pause();
        }, this);
    }

    update(deltaTime: number) {

    }

    btnEvents(event: any, data: any) {
        director.resume();

        this.scheduleOnce(() => {
            // this.capCanvas.remove();

            // eliminateGameManager.uiManager.camera.targetTexture = null;
            // eliminateGameManager.uiManager.UICamera.targetTexture = null;
            // this.uiBlur.spriteFrame.texture = null;
            // this.d3Blur.spriteFrame.texture = null;

            // this.uiBlur.spriteFrame = null;
            // this.d3Blur.spriteFrame = null;

            this.node.active = false;
            switch (data) {
                case "close":
                    eliminateGameManager.game.leaveGame().then(() => {
                        NDB.closeWebView();
                    })
                    break;
                case "replay":
                    resourceManager.loadSceneInBundle(`scene/${GameConfig.gameName}_GameScene`, GameConfig.gameName, () => {
                        director.loadScene(`${GameConfig.gameName}_GameScene`, (err, scene: Scene) => {
                            if (err) {
                                return;
                            }
                        });
                    });
                    break;
                case "goon":
                    console.log("继续", eliminateGameManager.uiManager.camera.targetTexture);
                    break;
            }
        }, 0.05);

    }
}

